package com.bzzoneit.newsys.service.admin.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bzzoneit.newsys.dao.admin.RoleMapper;
import com.bzzoneit.newsys.dao.admin.UserMapper;
import com.bzzoneit.newsys.entity.admin.Menu;
import com.bzzoneit.newsys.entity.admin.Role;
import com.bzzoneit.newsys.service.admin.RoleService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service
public class RoleServiceImple implements RoleService {

	protected static Logger logger =  LoggerFactory.getLogger("service");

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserMapper userMapper;

	public List<Role> getRoleList() {
		return roleMapper.getRoleList();
	}

	public void insertRole(Role role) {
		roleMapper.insertOne(role);

	}

	public void updateRole(Role role) {
		roleMapper.updateOne(role);

	}

	@Transactional
	public void deleteRole(Long id) {
		roleMapper.deleteUserRoleByRoleId(id); //t_user_role
		roleMapper.deleteRoleMenu(id); //t_role_menu
		roleMapper.deleteOne(id);//t_role
		
	}

	public Role getRole(Long id) {
		return roleMapper.selectOne(id);
	}

	public List<Role> getRoleMenuListByRoleId(Long id) {
		return roleMapper.getRoleMenuListByRoleId(id);
	}

	public void deleteRoleMenu(Long id) {
		roleMapper.deleteRoleMenu(id);
	}

	@Transactional
	public void insertRolemenu(Long id, List<Menu> list) {
		// 第一步删除所有的这个角色对应的
		roleMapper.deleteRoleMenu(id);
		if (list.size() > 0) {
			// 第二步批量保存
			List<Map<String, Object>> l = Lists.newArrayList();
			for (Menu m : list) {
				Map<String, Object> param = Maps.newHashMap();
				param.put("role_id", id);
				param.put("menu_id", m.getId());
				l.add(param);
			}
			roleMapper.insertRoleMenuBatch(l);
		}
	}

	public List<Role> getRoleListByuserid(Long id) {
		return roleMapper.getRoleListByuserid(id);
	}

	@Transactional
	public void saveUserRole(Long userid, String[] roleids) {
		// 第一步删除用户角色对应
		userMapper.deleteUserRole(userid);
		if (roleids.length > 0) {
			// 第二不批量保存 user_id role_id对应关系
			List<Map<String, Object>> l = Lists.newArrayList();
			for (String m : roleids) {
				Map<String, Object> param = Maps.newHashMap();
				param.put("role_id", m);
				param.put("user_id", userid);
				l.add(param);
			}
			roleMapper.insertUserRoleBatch(l);
		}
	}

}
